using System;
using System.Collections;
using System.Collections.Generic;
using Newtonsoft.Json;
using Sirenix.OdinInspector;
using UnityEngine;
using UnityEngine.Animations.Rigging;

public class VRig : MonoBehaviour
{
    //这里的Rig必须手动管理, 启用的时候才有权重, 否则默认全部都是0
    [LabelText("绑定成功")] public bool binded = false;
    [ShowIf("@OdinValue_rigVisiable"), PropertyRange(min: 0, max: 1), ShowInInspector, PropertyOrder(-1)]
    public float weight
    {
        get => OdinValue_rigVisiable ? rigGroup.weight : 0;
        set
        {
            if (OdinValue_rigVisiable) rigGroup.weight = value;
        }
    }

    [SerializeField, HideInInspector] private bool _rigEnable = false;
    private float _tempWeight = 0;

    public bool RigEnable
    {
        get => _rigEnable;
        set
        {
            if (value)
                weight = _tempWeight == 0 ? 1 : _tempWeight;
            else
            {
                _tempWeight = weight;
                weight = 0;
            }
            _rigEnable = value;
        }

    }
    private bool OdinValue_rigVisiable => rigBuilder != null && rigBuilder.layers.Count >= 1 && rigBuilder.layers[0].isInitialized;
    [HideInInspector] public Rig rigGroup;
    [HideInInspector] public RigBuilder rigBuilder;
    public void Init()
    {
        rigBuilder = gameObject.UniqueComponent<RigBuilder>();
    }
    public void OnUnLoad()
    {
        //卸载释放资源
        gameObject.RemoveComponent<RigBuilder>();
    }

    private void Start()
    {
        IKData.ForEach(x => { x.SetWeight(0); });
    }
    [Button("启用左手")]
    public void EnableHand()
    {
        var hand = IKData.Find(x => x.name == "LeftHand");
        hand .SetWeight(1);
    }
#if UNITY_EDITOR
    [LabelText("启用Rig功能")]
    [OnValueChanged("OdinCall_SwtichRigEnable")] public bool odin_rigEnable;
    private void OdinCall_SwtichRigEnable() => RigEnable = odin_rigEnable;
    [LabelText("启用LLM绑定Rig组件")][OnValueChanged("OdinCall_SwitchExtension_Rig")] public bool llmRigEnable;
    [HideInInspector] public VRig_LLMBindModule rig;
    public void OdinCall_SwitchExtension_Rig()
    {
        if (llmRigEnable)
        {
            rig = gameObject.UniqueComponent<VRig_LLMBindModule>();
        }
        else
        {
            gameObject.RemoveComponent<VRig_LLMBindModule>();
            rig = null;
        }
    }

    [LabelText("启用VTouch")][OnValueChanged("OdinCall_SwitchVTouch")] public bool vTouchEnable = false;

    public void OdinCall_SwitchVTouch()
    {
        if (vTouchEnable)
        {
            var vtouch = gameObject.UniqueComponent<VTouchManager>();
            vtouch.ApplyRigUnits();
        }
        else
        {
            var touch = gameObject.GetComponent<VTouchManager>();
            if (touch == null) return;
            touch.OnRemove();
            gameObject.RemoveComponent<VTouchManager>();
        }
    }

#endif


    // public void LookAtTarget(Transform target, float seconds = 2f)
    // {
    //     var oriPose = HeadRigTarget.transform.position;
    //     HeadRigTarget.DoTween(target.position, 0.5f);
    //     seconds.Delay(() =>
    //     {
    //         HeadRigTarget.DoTween(oriPose, 0.5f);
    //     });
    // }

    [LabelText("已绑定的IK节点")] public List<RigIKUnit> IKData;
    public void SetIKData(Rig rig, List<RigIKUnit> IKData)
    {
        this.rigGroup = rig;
        this.rigBuilder.layers = new() { new RigLayer(rig) };
        this.IKData = IKData;
    }

    [Serializable]
    public class RigIKUnit : IJsonable
    {
        public string name;
        [JsonIgnore] public Transform goal;
        [JsonIgnore] public Transform hint;
        [JsonIgnore] public Transform rootTransform;
        [JsonIgnore] public Transform midTransform;
        [JsonIgnore] public Transform tipTransform;
        [JsonIgnore] public TwoBoneIKConstraint bodyConstraint;
        [JsonIgnore] public MultiAimConstraint headConstraint;
        public string root;
        public string mid;
        public string tip;
        public bool isHead => name == "Head";
        public void SetWeight(float weight)
        {
            if (isHead)
            {
                //head逻辑还没写呢
            }
            else bodyConstraint.weight = weight;
        }
        public override string ToString()
        {
            return base.ToJson();
        }
    }
    public static List<RigIKUnit> ConvertToBoneBindUnits(VAvatarMaskID mask)
    {
        var boneBindUnits = new List<RigIKUnit>();

        if (mask.HasFlag(VAvatarMaskID.Head))
        {
            boneBindUnits.Add(new RigIKUnit
            {
                name = "Head",
                goal = GetTransformForBone("Head")
            });
        }
        if (mask.HasFlag(VAvatarMaskID.LeftHand))
        {
            boneBindUnits.Add(new RigIKUnit
            {
                name = "LeftHand",
                goal = GetTransformForBone("LeftHand")
            });
        }
        if (mask.HasFlag(VAvatarMaskID.RightHand))
        {
            boneBindUnits.Add(new RigIKUnit
            {
                name = "RightHand",
                goal = GetTransformForBone("RightHand")
            });
        }
        if (mask.HasFlag(VAvatarMaskID.LeftFoot))
        {
            boneBindUnits.Add(new RigIKUnit
            {
                name = "LeftFoot",
                goal = GetTransformForBone("LeftFoot")
            });
        }
        if (mask.HasFlag(VAvatarMaskID.RightFoot))
        {
            boneBindUnits.Add(new RigIKUnit
            {
                name = "RightFoot",
                goal = GetTransformForBone("RightFoot")
            });
        }

        return boneBindUnits;
    }
    private static Transform GetTransformForBone(string boneName) => null;
}
